package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.mess.ArticleEsMess;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-17 15:35
 */
@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    //freemarker配置对象
    @Autowired
    private Configuration configuation;

    //minio工具接口
    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    @Async
    public void createStaticUrl(ApArticle apArticle, String content){
        try {
            //2.freemarker生成静态html页面
            Template template = configuation.getTemplate("article.ftl");

            HashMap<String, Object> dataModel = new HashMap<>();

            //把内容json字符串转换成对象集合
            dataModel.put("content", JSON.parseArray(content));

            //将文件短暂存放在内存中 StringWriter存放在内存中而且是字符串的方式存放
            StringWriter out = new StringWriter();
            template.process(dataModel, out);

            //3.将html上传到minIO

            //输出流转换成输入流
            //try - with -resources
            try (ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8))) {
                String path = fileStorageService.uploadHtmlFile(null, apArticle.getId() + ".html", inputStream);

                // ** 4.将url写入到文章表
                //update xxx set static_url = #{path} and id = #{articleId}
                apArticleMapper.update(null, Wrappers.<ApArticle>lambdaUpdate()
                        .eq(ApArticle::getId, apArticle.getId())
                        .set(ApArticle::getStaticUrl, path)
                );


                //发送es更新消息
                ArticleEsMess articleEsMess = new ArticleEsMess();
                apArticle.setStaticUrl(path);
                BeanUtils.copyProperties(apArticle,articleEsMess);
                articleEsMess.setContent(content);
                kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(articleEsMess));
            }


        } catch (Exception e) {
            log.error("生成静态页面失败",e);
        }

    }
}
